<?php
namespace app\modules\exercise\models;

use app\modules\app\models\CheckAnswer;
use app\modules\cn\models\ExerciseCategory;
use app\modules\exercise\models\ExerciseListDetail as ExerciseDetail;
use yii;
use app\libs\Method;
use yii\db\ActiveRecord;

class ExerciseList extends ActiveRecord
{
    public static function tableName()
    {
        return '{{%exercise_list}}';
    }

    public function getData($where, $pageSize = 10, $page = 1)
    {
        $limit = " limit " . ($page - 1) * $pageSize . ",$pageSize";
        $sql = "select * from {{%exercise_list}} where $where order by id asc";
        $count = count(\Yii::$app->db->createCommand($sql)->queryAll());
        $data = Yii::$app->db->createCommand($sql . $limit)->queryAll();
        $pageStr = Method::getPagedRows(['count' => $count, 'pageSize' => $pageSize, 'rows' => 'models']);
        return ['data' => $data, 'pageStr' => $pageStr];
    }

    /**
     * @Title  [获取听力剑雅真题分类]
     * @Author Don
     * @Date   2021-04-25
     * @return [type]
     */
    public function getListenList($cateIds)
    {
        $list = array();
        $data = array();
        foreach ($cateIds as $value) {
            $res = Yii::$app->db->createCommand("SELECT cate_id,cate_id as id,name from {{%exercise_category}} where pid=$value")->queryAll();
            foreach ($res as $k => $v) {
                if ($v['name'] == '难度') {
                    unset($res[$k]);
                }
            }
            //三级列表名
            $data[] = $res;
            $list[] = $this->getlistenexerciserealnum($value);
        }
        return array($data, $list);
    }

    public function getlistenexerciserealnum($id)
    {
        $list = ExerciseCategory::find()->select('cate_id')->where("pid=$id AND isShow=1")->distinct()->asArray()->All();
        $list = array_column($list, 'cate_id');
        $data = [];
        if (!empty($list)) {
            // 查询重复标题
            foreach ($list as $value) {
                $tmp = self::find()->select(['name'])->where(['cate_id' => $value, 'pid' => 0])->distinct()->asArray()->All();
                $res[$value] = array_column($tmp, 'name');
            }
            // 过滤重复标题
            foreach ($res as $k => $v) {
                $doc = [];
                foreach ($v as $vc) {
                    $dov = self::find()->select('id,cate_id,pid,content_id,image,name,title,sort,viewCount,show,catName,level,type,topic,test_site,title_image,listeningFile')->where(['name' => $vc, 'cate_id' => $k])->asArray()->One();
                    $doc[] = $dov;
                }

                $data[$k] = $doc;
            }
        }
        return $data;
    }
    // 判断听力的整体test是否完成
    //by:sjeam
    public function listenProgressRate($data, $catId)
    {
        $userId = Yii::$app->session->get('userId');
        foreach ($data as $k => $v) {
            if ($v != false) {
                $data[$k]['userFinish'] = 0;
                $data[$k]['correctRate'] = 0;
                $data[$k]['userFinish'] = 0;
                $data[$k]['isCheck'] = 0;
                $tem = self::find()->asArray()->where('name="' . $v['name'] . '" and cate_id=' . $v['cate_id'])->all();
                $pids = implode(',', array_column($tem, 'content_id'));
                $name = str_replace(' - ', '-', str_replace('剑雅', 'jy', $v['name']));
                $data[$k]['id'] = $v['content_id'];
                $data[$k]['catId'] = $v['cate_id'];
//                $data[$k]['nameTest'] = substr($name, strrpos($name, '-') - 5, 5);
                $data[$k]['nameTest'] = substr(str_replace(' ','',$v['name']),stripos(str_replace(' ','',$v['name']),'test'),5);
                $data[$k]['count'] = count(ExerciseDetail::find()->asArray()->select('id')->where('pid in (' . $pids . ')')->all());
                if ($userId == false) {
                    $data[$k]['isOver'] = 0;
                    $data[$k]['continue'] = 0;
                } else {
                    $newid = Yii::$app->db->createCommand("select newid from {{%ielts_test_result}} where fid=" . $catId . " and pid  in (" . $pids . ") and userid=$userId and ISNULL(answer)=0 and LENGTH(trim(answer))>0 group by newid order by id desc")->queryOne();
                    if ($newid != false) {
                        $record = Yii::$app->db->createCommand("select testid from {{%ielts_test_result}} where fid=" . $catId . " and pid in (" . $pids . ") and userid=$userId and newid=" . $newid['newid'] . " and ISNULL(answer)=0 and LENGTH(trim(answer))>0 order by id desc")->queryAll();
                        $check=CheckAnswer::find()->where('resultid='.$newid['newid'].' and userid='.$userId.' and typeid=1')->one();
                        if ($data[$k]['count'] <= count($record)) {//数目相同，表示本章节完成
                            $data[$k]['isOver'] = 1;
                            $data[$k]['continue'] = 0;
                        } else {//继续做题
                            $data[$k]['isOver'] = 0;
                            $data[$k]['continue'] = 1;
                        }
                        $data[$k]['userFinish'] = count($record);
                        $data[$k]['isCheck'] = $check==false?0:1;
                    } else {//开始做题
                        $data[$k]['isOver'] = 0;
                        $data[$k]['continue'] = 0;
                    }
                }
                $total = Yii::$app->db->createCommand("select testid from {{%ielts_test_result}} where fid=" . $v['cate_id'] . " and pid in(" . $pids . ")  order by id desc")->queryAll();
                $true = Yii::$app->db->createCommand("select testid from {{%ielts_test_result}} where fid=" . $v['cate_id'] . " and pid in(" . $pids . ")  and result=1 order by id desc")->queryAll();
                $data[$k]['correctRate'] = (count($true) != false && count($total) != false) ? round(count($true) / count($total) * 100, 2) : 0;
            }
        }
        return $data;
    }

    //听力数据格式的修改统一
    public function listenFormat($data)
    {
        foreach($data as $k=>$v){
            if($v['parent']['description']!=false){
                if($v['parent']['article']!=false){
                    $data[$k]['parent']['description']=str_replace(['&lt;link/&gt;', '<link/>', '&lt;link &gt;', '<link />'],$v['parent']['article'],$v['parent']['description']);
                }
                $data[$k]['parent']['description']=str_replace(['&lt;input/&gt;', '<input/>', '&lt;link &gt;', '<input />'], '#&',$data[$k]['parent']['description']);
                if($v['parent']['image']!=false){
                    $data[$k]['parent']['description']=str_replace(['&lt;img/&gt;', '<img/>', '&lt;img &gt;', '<img />'], '<img src="https://ielts.thinkwithu.com'.$v['parent']['image'].'">',$data[$k]['parent']['description']);
                }
            }
            $data[$k]['parent']['listeningFile']=$v['parent']['listeningFile']!=false?$this->getlabeldelete($v['parent']['listeningFile']):array();
            if(count($data[$k]['parent']['listeningFile'])==2){//去掉第一个听力
                unset($data[$k]['parent']['listeningFile'][0]);
                $data[$k]['parent']['listeningFile']= array_values($data[$k]['parent']['listeningFile']);
            }
            $tem = trim(substr($v['parent']['title'],strrpos($v['parent']['title'],' ')));
            $temnum=$start = substr($tem,0,strrpos($tem,'-'));
            foreach($v['son'] as $key=>$val){
                $data[$k]['son'][$key]['answer']=$val['answer']!=false?$this->getlabeldelete($val['answer']):array();
                if($val['name']!='多选题'&&$val['name']!='配对选择题'){
                    $data[$k]['son'][$key]['qNum']=$temnum;
                    $temnum=$temnum+1;
                }else{
                    $data[$k]['son'][$key]['qNum']=$temnum.'-'.(($temnum+strlen($val['alternatives']))-1);
                    $temnum = $temnum+strlen($val['alternatives']);
                }
            }
        }
        return $data;
    }
    //阅读数据格式的修改统一
    public function format($data)
    {
        foreach($data as $k=>$v){
            if($v['parent']['sentenceNumber']!=false){
                $data[$k]['parent']['sentenceNumber']=explode("<br />",str_replace(PHP_EOL,'',nl2br($v['parent']['sentenceNumber'])));
            }else{
                $data[$k]['parent']['sentenceNumber']=array();
            }
            if($v['parent']['numbering'] == 8){
                $search = array('/<span class="answer-fill".*?>(.*?)<\/span>/is','/&lt;span class="answer-fill".*?&gt;(.*?)&lt;\/span&gt;/is');
                $tem=preg_replace($search,'#&',$v['parent']['description']);
                if (!is_array($tem)) {
                    $data[$k]['parent']['description']= $tem!=false?$tem:$v['parent']['description'];
                }
            }
            if($v['parent']['article']!=false){
                $tem='';
                if($v['parent']['type']==6){
                    $data[$k]['parent']['article']=$v['parent']['article']=str_replace(['<p>','</p>'],'',$v['parent']['article']);
                }
                if($v['parent']['numbering']==6){
                    $search = array('/<span class="answer-fill".*?>(.*?)<\/span>/is','/&lt;span class="answer-fill".*?&gt;(.*?)&lt;\/span&gt;/is');
                    $tem=preg_replace($search,'#&',$v['parent']['article']);
                }
                if($v['parent']['numbering']==2||$v['parent']['numbering']==5){
                    $search = array('/<input.*?>/is','/&lt;input.*?&gt/is');
                    $tem=preg_replace($search,'#&',$v['parent']['article']);
                }
                if (!is_array($tem)) {
                    $data[$k]['parent']['article'] = array();
                    $data[$k]['parent']['article'][0] = $tem!=false?$tem:$v['parent']['article'];
                }
                if($v['parent']['numbering']==4){
                    $data[$k]['parent']['article']=str_split($v['parent']['article']);
                }
            }else{
                $data[$k]['parent']['article']=array();
            }
            foreach($v['son'] as $key=>$val){
                if($val['description']!=false){
                    $data[$k]['son'][$key]['description']=explode("<br />",str_replace(PHP_EOL,'',nl2br($val['description'])));
                }else{
                    $data[$k]['son'][$key]['description']=array();
                }
            }
        }
        return $data;
    }
    // 百度编辑器 后台数据去P标签
    //by:sjeam
    public function getlabeldelete($dats)
    {
        $pregs = '/<p[^>]*>(.*)<\/p>/U';
        preg_match_all($pregs, $dats, $rel);
        return $rel[1];
    }

    /**
     * @Title  [判断阅读的整体test是否完成]
     * @Author Don
     * @Date   2021-04-28
     * @param  [type]
     * @return [type]
     */
    public function progressRate($data)
    {
        // f_d($data);
        $userId = Yii::$app->session->get('userId');
        foreach ($data as $k => $v) {
            $data[$k]['userFinish'] = 0;
            $data[$k]['correctRate'] = 0;
            $data[$k]['isCheck'] = 0;
            // 查询分类和名字下所有content_id
            $pid = self::find()->asArray()->select('content_id')->where('name=\'' . $v['name']."' and cate_id=".$v['cate_id'])->all();
            // f_d($pid);
            $pid = implode(',',array_column($pid,'content_id'));
            // f_d($pid);
            // 查询content_id为pid的所有题数
            $data[$k]['count'] = count(ExerciseDetail::find()->asArray()->select('content_id')->where('pid in(' . $pid.")")->all());
            if ($userId == false) { // 用户未登陆
                $data[$k]['isOver'] = 0;
                $data[$k]['continue'] = 0;
                $data[$k]['startId'] = ExerciseDetail::find()->asArray()->select('content_id')->where('pid=' . $v['content_id'])->orderBy('content_id asc')->one()['content_id'];
                $data[$k]['resultid'] = '';

            } else { // 用户已登陆
//                $userId = 4;
                $resultid = Yii::$app->db->createCommand("select resultid from {{%ielts_test_result}} where fid=" . $v['cate_id'] . " and pid in(" . $pid . ") and userid=$userId and ISNULL(answer)=0 and LENGTH(trim(answer))>0 group by resultid order by id desc")->queryOne();
                if ($resultid != false) {
                    $record = Yii::$app->db->createCommand("select testid from {{%ielts_test_result}} where fid=" . $v['cate_id'] . " and pid in(" . $pid . ") and userid=$userId and resultid=" . $resultid['resultid'] . " and ISNULL(answer)=0 and LENGTH(trim(answer))>0 order by id desc")->queryAll();//倒序的后改为正序
                    $check=CheckAnswer::find()->where('resultid='.$resultid['resultid'].' and userid='.$userId)->one();
                    if ($data[$k]['count'] <= count($record)) {//数目相同，表示本章节完成
                        $data[$k]['isOver'] = 1;
                        $data[$k]['continue'] = 0;
                        $data[$k]['startId'] = ExerciseDetail::find()->asArray()->select('content_id')->where('pid=' . $v['content_id'])->orderBy('content_id asc')->one()['content_id'];
                        $data[$k]['startPid'] = ExerciseDetail::find()->asArray()->select('pid')->where('content_id=' . $data[$k]['startId'])->orderBy('content_id asc')->one()['pid'];
                        $data[$k]['resultid'] = $resultid['resultid'];
                    } else {//继续做题
                        $data[$k]['isOver'] = 0;
                        $data[$k]['continue'] = 1;
//                        $data[$k]['startId'] = Content::find()->asArray()->select('id')->where('pid in (' . $pid . ') and id>' . $record[0]['testid'])->orderBy('id asc')->one()['id'];//原来按组做题
                        $data[$k]['startId'] = ExerciseDetail::find()->asArray()->select('content_id')->where('pid in (' . $pid . ')')->orderBy('content_id asc')->one()['content_id'];//按短文
                        $data[$k]['startPid'] =$data[$k]['startId']==false?'': ExerciseDetail::find()->asArray()->select('pid')->where('content_id=' . $data[$k]['startId'])->orderBy('content_id asc')->one()['pid'];
                        $data[$k]['resultid'] = $resultid['resultid'];
                    }
                    $data[$k]['userFinish']= count($record); // 用户已完成数量
                    $data[$k]['isCheck'] = $check == false ? 0 : 1;
                } else {//开始做题
                    $data[$k]['isOver'] = 0;
                    $data[$k]['continue'] = 0;
                    $data[$k]['startId'] = ExerciseDetail::find()->asArray()->select('content_id')->where('pid=' . $v['content_id'])->orderBy('content_id asc')->one()['content_id'];
                    $data[$k]['startPid'] ='';
                    $data[$k]['resultid'] = '';
                }
            }

            $data[$k]['nameTest'] =  substr(str_replace(' ','',$v['name']),stripos(str_replace(' ','',$v['name']),'test'),5);
            $total = Yii::$app->db->createCommand("select testid from {{%ielts_test_result}} where fid=" . $v['cate_id'] . " and pid in(" . $pid . ")  order by id desc")->queryAll();
            $true = Yii::$app->db->createCommand("select testid from {{%ielts_test_result}} where fid=" . $v['cate_id'] . " and pid in(" . $pid . ")  and result=1 order by id desc")->queryAll();
            $data[$k]['correctRate']= (count($true)!=false&&count($total)!=false)?round(count($true)/count($total)*100,2):0;

        }
        return $data;
    }
    // 判断口语的整体test是否完成
    //by:sjeam
    public function spokenProgressRate($data,$catId)
    {
        $userId = Yii::$app->session->get('userId');
        foreach ($data as $k => $v) {
            $data[$k]['userFinish']= 0;
            $pid = $v['id'];
            $dataTem = ExerciseList::find()->asArray()->select('name')->where('content_id =' . $pid)->one();
            $data[$k]['name'] = $dataTem['name'];
            $name=str_replace('剑雅', 'jy', $dataTem['name']);
            $data[$k]['nameTest'] = substr(str_replace(' ','',$data[$k]['name']),stripos(str_replace(' ','',$data[$k]['name']),'test'),5);
            $data[$k]['count'] = count(ExerciseDetail::find()->asArray()->select('id')->where('pid =' . $pid)->all());
            $data[$k]['answerId'] ='';
            if ($userId == false) {
                $data[$k]['isOver'] = 0;
                $data[$k]['continue'] = 0;
                $data[$k]['startId'] = ExerciseDetail::find()->asArray()->select('content_id as id')->where('pid=' . $v['id'])->orderBy('id asc')->one()['id'];
                $data[$k]['resultid'] ='';
            } else {
                $resultid = Yii::$app->db->createCommand("select resultid,id from {{%ielts_test_result}} where fid=" . $catId . " and pid =" . $v['id'] . " and userId=$userId and ISNULL(answer)=0 and LENGTH(trim(answer))>0 group by resultid order by id desc")->queryOne();
                if ($resultid != false) {
                    $record = Yii::$app->db->createCommand("select testid from {{%ielts_test_result}} where fid=" . $catId . " and pid =" . $v['id'] . " and userId=$userId and resultid=" . $resultid['resultid'] . " and ISNULL(answer)=0 and LENGTH(trim(answer))>0 order by id desc")->queryAll();//倒序的后改为正序
                    if ($data[$k]['count'] <= count($record)) {//数目相同，表示本章节完成
                        $data[$k]['isOver'] = 1;
                        $data[$k]['continue'] = 0;
                        $data[$k]['startId'] = ExerciseDetail::find()->asArray()->select('content_id as id')->where('pid =' . $pid)->orderBy('id asc')->one()['id'];
                        $data[$k]['resultid'] = $resultid['resultid'];
                        $data[$k]['answerId'] = $resultid['id'];
                    } else {//继续做题
                        $data[$k]['isOver'] = 0;
                        $data[$k]['continue'] = 1;
                        $data[$k]['startId'] =  ExerciseDetail::find()->asArray()->select('content_id as id')->where('pid =' . $pid )->orderBy('id asc')->one()['id'];//原来按组做题
                        $data[$k]['resultid'] = $resultid['resultid'];
                    }
                    $data[$k]['userFinish']= count($record);
                } else {//开始做题
                    $data[$k]['isOver'] = 0;
                    $data[$k]['continue'] = 0;
                    $data[$k]['startId'] = ExerciseDetail::find()->asArray()->select('content_id as id')->where('pid =' . $pid)->orderBy('id asc')->one()['id'];
                    $data[$k]['startPid'] ='';
                    $data[$k]['resultid'] = '';
                }
            }
        }
        return $data;
    }

    public static function getMaxContentId(){
        $id1 = ExerciseList::find()->orderBy('content_id desc')->asArray()->one();
        $id2 = ExerciseDetail::find()->orderBy('content_id desc')->asArray()->one();
        $id = max($id1['content_id'],$id2['content_id']);
        return $id+2;
    }
}
